package pers.twm.mybatis.ui;

import com.intellij.execution.DefaultExecutionResult;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.configurations.RunProfileState;
import com.intellij.execution.filters.TextConsoleBuilder;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.impl.ConsoleViewImpl;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.*;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.ex.ToolWindowManagerListener;
import com.intellij.ui.content.Content;
import com.intellij.util.DocumentUtil;
import com.intellij.util.IconUtil;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import pers.twm.mybatis.executor.SqlLogExecutor;

import javax.swing.*;
import java.awt.*;

import static pers.twm.mybatis.constant.Constant.DESCRIPTION;
import static pers.twm.mybatis.util.IconsUtil.MY_BATIS;

/**
 * @ClassName LogExecutor
 * @Description TODO
 * @Author tianwanming
 * @Date 2023/2/27 15:26
 * @Version 1.0
 */
public class LogExecutor implements Disposable {
    public static Key<LogExecutor> KEY = Key.create(LogExecutor.class.getName());
    /**
     * Project
     */
    private Project project = null;



    /**
     * 停止 ToolWindow
     */

    private ConsoleView consoleView = null;

    public ConsoleView getConsoleView() {
        return consoleView;
    }

    public LogExecutor(@NotNull Project project, Runnable rerun) {
        this.project = project;
        project.putUserData(KEY,this);
    }

    private JPanel createConsolePanel(ConsoleView consoleView) {
        final JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(consoleView.getComponent(), BorderLayout.CENTER);
        return panel;
    }


    public void run() {

        this.consoleView = createConsoleView();

        // 返回定义的 Executor
        Executor executor = SqlLogExecutor.getInstance();
        if (executor == null) {
            return;
        }

        // 创建 RunnerLayoutUi
        final RunnerLayoutUi.Factory factory = RunnerLayoutUi.Factory.getInstance(project);
        RunnerLayoutUi layoutUi = factory.create("SQL Log", "SQL Log", "SQL Log", project);

        // 创建 panel
        final JPanel panel = createConsolePanel(consoleView);

        // 创建描述信息
        RunContentDescriptor descriptor = new RunContentDescriptor(new RunProfile() {
            @Nullable
            @Override
            public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment environment) throws ExecutionException {
                return null;
            }

            @NotNull
            @Override
            public String getName() {
                return DESCRIPTION;
            }

            @Nullable
            @Override
            public Icon getIcon() {
                return MY_BATIS;
            }
        }, new DefaultExecutionResult(), layoutUi);

        descriptor.setExecutionId(System.nanoTime());

        final Content content = layoutUi.createContent("SQL Log", panel, "SQL Log", AllIcons.Debugger.Console, panel);

        content.setCloseable(false);

        layoutUi.addContent(content);

        // 新增左边工具条
        layoutUi.getOptions().setLeftToolbar(createActionToolbar(consoleView), "RunnerToolbar");

        Disposer.register(this, consoleView);

        RunContentManager manager = RunContentManager.getInstance(project);
        manager.showRunContent(executor, descriptor);

    }

    private ActionGroup createActionToolbar(ConsoleView consoleView) {
        final DefaultActionGroup actionGroup = new DefaultActionGroup();

        for (AnAction consoleAction : consoleView.createConsoleActions()) {
            actionGroup.add(consoleAction);
        }
        return actionGroup;
    }

    private ConsoleViewImpl createConsoleView() {
        TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(project);
        final ConsoleViewImpl console = (ConsoleViewImpl) consoleBuilder.getConsole();
        // init editor
        return console;
    }

    @Override
    public void dispose() {
        Disposer.dispose(this);
    }


    public void printSql(String sql,int val,String logPrefix) {

        consoleView.print(String.format("----------- %s ----------- %s\n", val, logPrefix), ConsoleViewContentType.LOG_DEBUG_OUTPUT);

        consoleView.print(sql, ConsoleViewContentType.USER_INPUT);

    }



}
